import './BooksDetail.css'
import { message } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import { book, articlelist, articlecontent } from '../../assets/api/booksdetail';
import BookContent from '../BookContent/BookContent';
import ReadBar from '../ReadBar/ReadBar';
export default function BooksDetail(props) {
    const [artindex, setartindex] = useState(0);//章节序号
    const [artcontent, setartcontent] = useState("");//章节内容
    const [artlist, setartlist] = useState([]);//章节列表
    const [booksitr, setbooksitr] = useState({});//书籍信息
    const [startx, setStartx] = useState(0);
    const [starty, setStarty] = useState(0);
    const [lineheight, setlineheight] = useState(0);
    const [readbarshow, setreadbarshow] = useState(false);
    const [flag, setflag] = useState(false);//是否加入书架
    const [contentfontsize, setcontentfontsize] = useState(0);
    const movecontent = useRef();
    function changeartindex(index) {
        if (index === -1 || index === artlist.length) {
            return;
        }
        setartindex(index);
        let flag = false;//判断章节是否有缓存
        let list = window.sessionStorage.getItem("reading");
        list = JSON.parse(list);
        //已经缓存当前章节
        list.forEach(ele => {
            if (ele.index === index) {
                setartcontent(ele.detail);
                flag = true;
                save(index);
            }
        })
        if (!flag) {
            message.loading(
                {
                    key: 1,
                    content: <span>加载中</span>,
                    className: "toast",
                    duration: 0,
                }
            )
            articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[index].secId }).then(contentdata => {
                list.push({ index, detail: contentdata.data.content });
                save(index);
                setartcontent(contentdata.data.content);
                message.destroy(1);
            })
        }
    }
    useEffect(() => {
        if (props.booksdetailshow === 1) {
            //如果阅读记录中读过这本书
            props.reading.forEach(ele => {
                if (ele.id === props.nowbook) {
                    setartindex(ele.artindex);
                    movecontent.current.style.transition = "all 0.3s ease-in-out";
                    movecontent.current.style.left = "0px";
                }
            })
            setflag((props.bookshelf.indexOf(props.nowbook) !== -1));
        }


    }, [props.booksdetailshow]);
    useEffect(() => {
        if (props.nowbook === "") {
            return;
        }
        //如果阅读记录中读过这本书
        props.reading.forEach(ele => {
            if (ele.id === props.nowbook) {
                setartindex(ele.artindex);
            }
        })
        articlelist({ source_uuid: props.nowbook }).then(data => {
            console.log(data);
            setartlist(data.data.catalog);
            console.log(artlist);
            if (!artindex) {
                book({ id: props.nowbook, title: data.data.book.title }).then(res => {
                    console.log(res);
                    setbooksitr({
                        url: data.data.book.coverImage,
                        title: data.data.book.title,
                        author: data.data.book.author,
                        content: res.feed.entry.content.text,
                        words: parseInt(res.feed.entry["pris:book"].words / 10000),
                        times: res.feed.entry["pris:subscribe"].clicksCount.split("万")[0].split("亿"),
                    })

                })
            }

        });

    }, [props.nowbook]);
    function changeflag() {
        message.info(
            {
                icon: <></>,
                key: 1,
                content: <div>加入书架成功</div>,
                className: "toast",
                duration: 1,
            }
        )
        setflag(true);
        props.addbookshelf(props.nowbook);
    }
    //判断章节是否已缓存
    function judge(list, index) {
        let flag = false;
        list.forEach(ele => {

            if (ele.index == index) {
                flag = true;
            }
        });
        return flag;
    }
    //对上下章进行缓存
    function save(index = artindex) {
        let contentlist = window.sessionStorage.getItem("reading");
        contentlist = JSON.parse(contentlist);

        if (index === 0) {
            // articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[artindex-1].secId }).then(contentdatalast)
            if (!judge(contentlist, (index + 1))) {
                articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[index + 1].secId }).then(contentdatanext => {
                    contentlist.push({ index: index + 1, detail: contentdatanext.data.content });
                    window.sessionStorage.setItem("reading", JSON.stringify(contentlist));
                })
            }

        } else if (index === artlist.length - 1) {
            if (!judge(contentlist, (index - 1))) {
                articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[index - 1].secId }).then(contentdatalast => {
                    contentlist.push({ index: index - 1, detail: contentdatalast.data.content });
                    window.sessionStorage.setItem("reading", JSON.stringify(contentlist));
                })
            }

        } else {
            let p1, p2;
            if (!judge(contentlist, (index + 1))) {
                console.log(!judge(contentlist, (index + 1)));
                p1 = articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[index + 1].secId }).then(contentdatanext => {
                    contentlist.push({ index: index + 1, detail: contentdatanext.data.content });
                })
            }
            if (!judge(contentlist, (index - 1))) {
                p2 = articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[index - 1].secId }).then(contentdatalast => {
                    contentlist.push({ index: index - 1, detail: contentdatalast.data.content });
                })
            }
            Promise.all([p1, p2]).then(() => {
                window.sessionStorage.setItem("reading", JSON.stringify(contentlist));
            })
        }
    }
    function changereadbar() {
        setreadbarshow(!readbarshow);
    }
    useEffect(() => {
        if (artlist.length === 0) {
            return;
        }
        let sessionreading = [];
        window.sessionStorage.setItem("reading", JSON.stringify(sessionreading));
        articlecontent({ source_uuid: props.nowbook, content_uuid: artlist[artindex].secId }).then(contentdata => {
            console.log(contentdata);
            let list = window.sessionStorage.getItem("reading");
            list = JSON.parse(list);
            list.push({ index: artindex, detail: contentdata.data.content });
            window.sessionStorage.setItem("reading", JSON.stringify(list));
            save();
            setartcontent(contentdata.data.content);
            if (artindex) {
                movecontent.current.style.transition = "all 0.3s ease-in-out";
                movecontent.current.style.left = "0px";
            } else {
                message.destroy(1);
                props.showbooksdetail();
            }
        })
    }, [artlist]);

    //初始化
    function init() {
        setartindex(0);
    }
    function hidebooksdetail() {
        setreadbarshow(false);
        movecontent.current.style.transition = "all 0.3s ease-in-out";
        movecontent.current.style.left = window.screen.width + "px";
        props.hidebooksdetail(props.nowbook, init, artindex);
    }

    const handleTouchStartDetail = (e) => {
        setStartx(e.touches[0].pageX);
        setStarty(e.touches[0].pageY);
        movecontent.current.style.transition = "none";
    };
    const handleTouchMoveDetail = (e) => {
        movecontent.current.style.left = window.screen.width - (startx - e.touches[0].pageX) + "px";
    };
    const handleTouchEndDetail = (e) => {
        let endx, endy;
        if (e.target.className === "add") {
            return;
        }
        endx = e.changedTouches[0].pageX;
        endy = e.changedTouches[0].pageY;
        let direction = getDirection(startx, starty, endx, endy);
        switch (direction) {
            case 0:
                changereadbar();
                console.log("未滑动！");
                break;
            case 1:
                console.log("向上！");
                break;
            case 2:
                console.log("向下！");
                break;
            case 3:
                movecontent.current.style.transition = "all 0.3s ease-in-out";
                movecontent.current.style.left = "0px"
                console.log("向左！");
                break;
            case 4:
                console.log("向右！");
                break;
            default:
        }
    };
    //根据接触和离开判断方向 1向上 2向下 3向左 4向右 0未发生滑动（[Math.abs][4]）
    const getDirection = (startx, starty, endx, endy) => {
        let angx = endx - startx;
        let angy = endy - starty;
        let result = 0;

        if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
            return result;
        }
        let angle = getAngle(angx, angy);
        if (angle >= -135 && angle <= -45) {
            result = 1;
        } else if (angle > 45 && angle < 135) {
            result = 2;
        } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;

        }

        return result;
    }
    //触摸点和离开点连线与[x轴角度][3]
    const getAngle = (angx, angy) => {
        return Math.atan2(angy, angx) * 180 / Math.PI;
    };
    return (
        <div
            className={'booksdetailbox ' + (props.show ? "show" : "")}>
            <BookContent
                changereadbar={changereadbar}
                artindex={artindex}
                movecontent={movecontent}
                contentfontsize={contentfontsize}
                artcontent={artcontent}
                lineheight={lineheight}
                changeartindex={changeartindex}
            />
            <ReadBar
                changeartindex={changeartindex}
                show={readbarshow}
                setlineheight={setlineheight}
                booksitr={booksitr}
                setcontentfontsize={setcontentfontsize}
                artindex={artindex}
                setreadbarshow={setreadbarshow}
                artlist={artlist}
                flag={flag}
                changeflag={changeflag}
                hidebooksdetail={hidebooksdetail}
            />
            <div className="firstbox"
                onTouchStart={handleTouchStartDetail}
                onTouchMove={handleTouchMoveDetail}
                onTouchEnd={handleTouchEndDetail}
            >
                <div className="booksdetailcontent">
                    <div className="top">
                        <div className="bookface">
                            <img src={booksitr.url} alt="" />
                        </div>
                        <div className="booktitle">{booksitr.title}</div>
                        <div className="bookauthor">{booksitr.author}</div>
                    </div>
                    <div className="bottom">
                        <div className="itr">
                            {booksitr.content}
                        </div>
                        <div className="detail">
                            <div className="left">
                                <div className="click">字数</div>
                                <div className="times"><span>{booksitr.words}</span>万字</div>
                            </div>
                            <div className="right">
                                <div className="click">点击</div>
                                <div className="times"><span>{booksitr.times}</span>万次</div>
                            </div>
                        </div>
                        {
                            flag ? <div className="alr">已加入书架</div> : <div className="add" onClick={changeflag}>加入书架，随时追书</div>
                        }
                    </div>
                </div>
            </div>
        </div>
    );
}
